﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsTheme.Helper
{
    class TextHelper
    {
        /// <summary>
        /// 过滤非法字符
        /// </summary>
        /// <param name="str"></param>
        /// <returns>若有，则返回处理完的字符串，若没有，则返回""</returns>
        public static string ReplaceBadChar(string str)
        {
            if (string.IsNullOrEmpty(str))
                return "";

            StringBuilder rBuilder = new StringBuilder(str);

            foreach (char rInvalidChar in Path.GetInvalidFileNameChars())
                rBuilder.Replace(rInvalidChar.ToString(), string.Empty);

            str = rBuilder.ToString().Trim() ;
            return str;
        }
        /// <summary>
        /// 读取文本文件的方法
        /// </summary>
        /// <param name="FilePath">文件路径</param>
        /// <param name="defaultcoding">文件编码格式，默认utf8</param>
        /// <returns></returns>
        public static string ReaderText(string FilePath, Encoding defaultcoding = null) {

            String Readtext = "";
            Encoding ReadCoding = Encoding.UTF8;
            if (defaultcoding != null)
                ReadCoding = defaultcoding;
            try
            {
                Readtext = File.ReadAllText(FilePath,ReadCoding);

            }
            catch (Exception ex) {
                PrintLog.Log(ex);
                PrintLog.Log("传入的参数为FilePath{0}/r/ndefaultcoding{1}",FilePath, defaultcoding.ToString());
            }
            return Readtext;
        }

        public static bool SaveText(string FilePath, String content, Encoding defaultcoding = null) {

            Encoding ReadCoding = Encoding.UTF8;
            if (defaultcoding != null)
                ReadCoding = defaultcoding;
            try
            {
             File.WriteAllText(FilePath, content, ReadCoding);
                return true;
            }
            catch (Exception ex)
            {
                PrintLog.Log(ex);
                PrintLog.Log("传入的参数为FilePath{0}/r/ndefaultcoding{1}/r/n文本{2}", FilePath, defaultcoding.ToString(), content);
            }
            return false;
        }

    }
}
